import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  'content-type': 'application/x-www-form-urlencoded',
  baseURL: '',
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Authorization'] = 'Bearer ' + getToken()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data

    if (parseInt(response.status / 100) !== 2) {
      if (response.status === 500) {
        Message({
          message: '请求超时！',
          type: 'error',
          duration: 5 * 1000
        })
      } else if (response.status === 401) {
        Message({
          message: '权限不足！',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error('Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
